package com.itany;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Author：汤小洋
 * Date：2022-10-26 11:43
 * Description：<描述>
 */
public class Test06_函数式接口 {
    public static void main(String[] args) {
        /**
         * Comsumer
         */
        Consumer<String> c = t -> System.out.println(t);
        c.accept("hello");

        /**
         * Supplier
         */
        Supplier<Integer> s = () -> new Random().nextInt(100);
        System.out.println(s.get());

        /**
         * Function
         */
        Function<Integer, Integer> f = t -> new Random().nextInt(t + 1);
        System.out.println(f.apply(10));

        /**
         * Predicate
         */
        Predicate<Integer> p = t -> t % 2 == 0;
        System.out.println(p.test(12));

        List<String> list = Arrays.asList("aaa","bb", "c", "dddd", "ee", "fff");
        // 筛选出长度大于2的字符串
        List<String> newList = strFilter(list, t -> t.length() > 2);
        System.out.println(newList);

    }

    /**
     * 按指定规则过滤字符串，返回过滤后的字符串集合
     */
    public static List<String> strFilter(List<String> list, Predicate<String> filter) {
        ArrayList<String> newList = new ArrayList<>();
        for (String str : list) {
            if (filter.test(str)) {
                newList.add(str);
            }
        }
        return newList;
    }

}
